package com.b2c.erp.controller;


import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.DataRow;
import com.b2c.entity.GoodsCategoryAttributeEntity;
import com.b2c.entity.GoodsSpecAttrEntity;
import com.b2c.entity.erp.vo.*;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.StockService;
import com.b2c.erp.req.GoodsSearchReq;
import com.b2c.erp.response.ApiResult;
import com.b2c.erp.response.SpecListResp;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 描述：
 *
 * @author qlp
 * @date 2019-05-28 16:10
 */
@RequestMapping(value = "/ajax_goods")
@RestController
public class AjaxGoodsController {
    @Autowired
    private StockService stockService;
    @Autowired
    private ErpGoodsService goodsService;
    @Autowired
    private ErpUserActionLogService logService;
    private static Logger log = LoggerFactory.getLogger(AjaxGoodsController.class);
    /**
     * 获取分类json
     *
     * @return
     */
    @RequestMapping(value = "/json_category", method = RequestMethod.POST)
    public ApiResult<String> getJsonCategory() {
        String cateJson = stockService.getCategoryString();
        return new ApiResult<>(0, cateJson);
    }


//    @RequestMapping(value = "/goods_add", method = RequestMethod.POST)
//    public ApiResult<String> goodsAdd(Model model, HttpServletRequest request) {
//        String goodsName = request.getParameter("spname");  //商品名称
//        String number = request.getParameter("spcode");  //商品编号
//        Integer categoryId = Integer.parseInt(request.getParameter("spsort"));  //商品分类id
//        Integer unitId = 0; //计量单位
//
//        String[] specNumber = request.getParameterValues("code[]");  //规格编号
//        String[] specName = request.getParameterValues("type[]"); //规格名
//        String[] lowQty = request.getParameterValues("min[]"); //最低库存
//        String[] highQty = request.getParameterValues("max[]"); //最高库存
//
//        //校验
//        if (StringUtils.isEmpty(request.getParameter("spunit"))) return new ApiResult<>(400, "请选择计量单位");
//        unitId = Integer.parseInt(request.getParameter("spunit"));
//        Integer locationId = 0; //仓库id
//        //校验
//        if (StringUtils.isEmpty(request.getParameter("locationId"))) return new ApiResult<>(400, "请选择仓库");
//        locationId = Integer.parseInt(request.getParameter("locationId"));
//
//        int reservoirId = 0;
//        if (StringUtils.isEmpty(request.getParameter("reservoirId"))) return new ApiResult<>(400, "请选择库区");
//        reservoirId = Integer.parseInt(request.getParameter("reservoirId"));
//
//        int shelfId = 0;
//        if (StringUtils.isEmpty(request.getParameter("shelfId"))) return new ApiResult<>(400, "请选择货架");
//        shelfId = Integer.parseInt(request.getParameter("shelfId"));
//
//        if (stockService.ifExsitNumber(number) > 0) return new ApiResult<>(400, number + ":商品编号已存在");
//
//        /**********组合要添加的商品数据***********/
//        List<GoodsExcelVo> goodsList = new ArrayList<>();
//        if (specNumber != null && specNumber.length > 0) {
//            Integer length = specNumber.length;
//            for (int i = 0; i < length; i++) {
////                for (int j = i ; j < length; j++) {
////                    if (specNumber[i].equals(specNumber[j])) {
////                        return new ApiResult<>(400, "存在相同的规格编号");
////                    }
////
////                }
//                GoodsExcelVo goods = new GoodsExcelVo();
//                goods.setNumber(number);
//                goods.setLocationId(locationId);
//                goods.setCategoryId(categoryId);
//                goods.setReservoirId(reservoirId);
//                goods.setShelfId(shelfId);
//                goods.setUnitId(unitId);
//                goods.setSpecNumber(specNumber[i]);
//                goods.setSpecName(specName[i]);
//                goods.setMixStock(Integer.parseInt(lowQty[i]));
//                goods.setMaxStock(Integer.parseInt(highQty[i]));
//                goods.setTitle(goodsName);
//                goods.setStock(0);
//                goodsList.add(goods);
//            }
//        }
//
//        ResultVo<Integer> resultVo = goodsService.goodsAddNew(goodsList);
//        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
//            return new ApiResult<>(0, "SUCCESS");
//        } else {
//            return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
//        }
//        //添加商品信息
////        Integer goodsId = stockService.editGoods(goodsName,number,categoryId,unitId,0);
////
////        //保存规格信息
////        if (specNumber != null && specNumber.length >0){
////            for (int i=0; i<specNumber.length; i++){
////                if (stockService.ifExsitSpecNumber(specNumber[i])>0) return new ApiResult<>(400, specNumber[i] + ":规格编号已存在，请勿重复添加");
////                stockService.editGoodsSpec(specNumber[i],specName[i],lowQty[i],highQty[i],goodsId,0,locationId);
////            }
////        }
//
//
//    }

    /**
     * 导出商品
     */
    @RequestMapping(value = "/goods_export",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public void outExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取前台传过来的ids
        String str = "";
        if (!StringUtils.isEmpty(request.getParameter("str"))) {
            str = request.getParameter("str");
        }
        Integer categoryId = null;
        if (!StringUtils.isEmpty(request.getParameter("categoryId"))) {
            categoryId = Integer.parseInt(request.getParameter("categoryId"));
        }
        Integer status = null;
        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
        }

        List<ErpGoodsListVo> list = stockService.getGoodsListExport(str,categoryId,status,null,null);
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        sheet.setColumnWidth(0, 5000);
        sheet.setColumnWidth(1, 5000);
        sheet.setColumnWidth(2, 5000);
        sheet.setColumnWidth(3, 6000);
        sheet.setColumnWidth(4, 5000);
        sheet.setColumnWidth(5, 5000);
        sheet.setColumnWidth(6, 4000);
        sheet.setColumnWidth(7, 4000);
        sheet.setColumnWidth(8, 4000);
        sheet.setColumnWidth(9, 4000);
        sheet.setColumnWidth(10, 2000);

        // 设置表头字体样式
        HSSFFont columnHeadFont = workbook.createFont();
        columnHeadFont.setFontName("宋体");
        columnHeadFont.setFontHeightInPoints((short) 10);

        // 列头的样式
        HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
        columnHeadStyle.setFont(columnHeadFont);
        // 上下居中
        columnHeadStyle.setLocked(true);
        columnHeadStyle.setWrapText(true);
        // 设置普通单元格字体样式
        HSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 14);

        //创建Excel工作表第一行
        HSSFRow row0 = sheet.createRow(0);
        // 设置行高
        row0.setHeight((short) 500);
        HSSFCell cell = row0.createCell(0);
        //设置单元格内容
        cell.setCellValue(new HSSFRichTextString("商品标题"));
        //设置单元格字体样式
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(1);
        cell.setCellValue(new HSSFRichTextString("商品编码"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(2);
        cell.setCellValue(new HSSFRichTextString("商品分类"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(3);
        cell.setCellValue(new HSSFRichTextString("面料"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(4);
        cell.setCellValue(new HSSFRichTextString("季节"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(5);
        cell.setCellValue(new HSSFRichTextString("年份"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(6);
        cell.setCellValue(new HSSFRichTextString("尺寸"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(7);
        cell.setCellValue(new HSSFRichTextString("重量"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(8);
        cell.setCellValue(new HSSFRichTextString("采购价"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(9);
        cell.setCellValue(new HSSFRichTextString("建议直播价"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(10);
        cell.setCellValue(new HSSFRichTextString("规格数"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(11);
        cell.setCellValue(new HSSFRichTextString("库存总数"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(12);
        cell.setCellValue(new HSSFRichTextString("备注"));
        cell.setCellStyle(columnHeadStyle);
        cell = row0.createCell(13);
        cell.setCellValue(new HSSFRichTextString("状态"));
        cell.setCellStyle(columnHeadStyle);


        // 循环写入数据
        for (int i = 0; i < list.size(); i++) {

            ErpGoodsListVo item = list.get(i);

            HSSFRow row = sheet.createRow(i + 1);

            cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString(item.getName()));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(1);
            cell.setCellValue(new HSSFRichTextString(item.getNumber()));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(2);
            if (StringUtils.isEmpty(item.getCategory())) item.setCategory("");
            cell.setCellValue(new HSSFRichTextString(item.getCategory()));
            cell.setCellStyle(columnHeadStyle);


            cell = row.createCell(3);
            if (StringUtils.isEmpty(item.getAttr5())) item.setAttr5("");
            cell.setCellValue(new HSSFRichTextString(item.getAttr5()));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(4);
            if (StringUtils.isEmpty(item.getAttr1())) item.setAttr1("");
            cell.setCellValue(new HSSFRichTextString(item.getAttr1()));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(5);
            if (StringUtils.isEmpty(item.getAttr4())) item.setAttr4("");
            cell.setCellValue(new HSSFRichTextString(item.getAttr4()));
            cell.setCellStyle(columnHeadStyle);


            //尺寸
            String cc = "";
                    if(item.getLength() > 0)   cc+= "衣长："+item.getLength()+"cm\r\n";
            if(item.getHeight() > 0)    cc+="袖长："+item.getHeight()+"cm\n";
            if(item.getWidth() > 0) cc+="胸阔："+item.getWidth()+"cm\n";
            if(item.getWidth1() > 0) cc+="肩阔："+item.getWidth1()+"cm\n";
            if(item.getWidth2() > 0) cc+="腰阔："+item.getWidth2()+"cm\n";
            if(item.getWidth3() > 0) cc+="臀阔："+item.getWidth3()+"cm\n";

            cell = row.createCell(6);
            cell.setCellValue(new HSSFRichTextString(cc));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(7);
            cell.setCellValue(new HSSFRichTextString(item.getWeight()+"g"));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(8);
            cell.setCellValue(new HSSFRichTextString(item.getCostPrice()+""));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(9);
            cell.setCellValue(new HSSFRichTextString(item.getSalePrice()+""));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(10);
            cell.setCellValue(new HSSFRichTextString(item.getSpecCount()+""));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(11);
            cell.setCellValue(new HSSFRichTextString(item.getQty()+""));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(12);

            cell.setCellValue(new HSSFRichTextString(item.getRemark()));
            cell.setCellStyle(columnHeadStyle);

            cell = row.createCell(13);
            String statusStr = "已下架";
            if(item.getStatus().intValue()  ==1 ) statusStr="销售中";
            cell.setCellValue(new HSSFRichTextString(statusStr));
            cell.setCellStyle(columnHeadStyle);

        }

        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf=new SimpleDateFormat("yyyyMMddHHmmss");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String(("goods" + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败");
            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                    "/ajax_goods/export","导出商品 , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"导出失败");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败");
            //添加系统日志
            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                    "/ajax_goods/export","导出商品 , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"导出失败");
            e.printStackTrace();
        }
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_goods/export","导出商品 , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

        return;
    }

    /**
     * 导出商品SKU
     * @param model
     * @param req
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/goods_spec_export", method = RequestMethod.GET)
    public void purchasePutDetail(Model model, HttpServletRequest req, HttpServletResponse response) {

        List<ErpGoodsSpecStockVo> lists = stockService.goodsSkuListExport();
//        var lists = stockService.specStockByExport();//invoiceService.invoiceItemPOList();

        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "spec_stock_info_export_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("");
        cell = row.createCell(0);
        cell.setCellValue("商品编码");
        cell = row.createCell(1);
        cell.setCellValue("SKU编码");
        cell = row.createCell(2);
        cell.setCellValue("规格");
        cell = row.createCell(3);
        cell.setCellValue("当前库存");
        cell = row.createCell(4);
        cell.setCellValue("采购价");


        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            ErpGoodsSpecStockVo itemVo = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(itemVo.getNumber());
            //商品名称
            cell = row.createCell(1);
            cell.setCellValue(itemVo.getSpecNumber());
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getColorValue()+itemVo.getSizeValue());

            cell = row.createCell(3);
            cell.setCellValue(itemVo.getQty());
            //采购价
            cell = row.createCell(4);
            cell.setCellValue(String.format("%.2f",itemVo.getCostPrice()));
        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }

    /**
     * 批量导入商品(excel)
     *
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
//    @RequestMapping(value = "/goods_excel_import", method = RequestMethod.POST)
//    public ApiResult<Integer> orderSendExcel(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {
//
//        String fileName = file.getOriginalFilename();
//        String dir = System.getProperty("user.dir");
//        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
//        System.out.println(destFileName);
//        File destFile = new File(destFileName);
//        file.transferTo(destFile);
//
//        System.out.println("上传成功");
//        System.out.println("开始读取EXCEL内容");
//
//        Workbook workbook = null;
//        InputStream fis = null;
//
//        //要导入的商品
//        var goodsList = new ArrayList<GoodsExcelVo>();
//
//
//        try {
//            fis = new FileInputStream(destFileName);
//
//            if (fileName.toLowerCase().endsWith("xlsx")) {
//                workbook = new XSSFWorkbook(fis);
//            } else if (fileName.toLowerCase().endsWith("xls")) {
//                workbook = new HSSFWorkbook(fis);
//            }
//
//            Sheet sheet = workbook.getSheetAt(0);
//
//            //得到行的迭代器
//            Iterator<Row> rowIterator = sheet.iterator();
//            int rowCount = 0;
//            //循环每一行
//            while (rowIterator.hasNext()) {
//                Row row = rowIterator.next();
//                //从第二行开始
//                if (rowCount > 0) {
//                    System.out.print("第" + (rowCount++) + "行  ");
//
//                    var goodsExcelVo = new GoodsExcelVo();
//                    try {
//                        //title
//                        goodsExcelVo.setTitle(row.getCell(0).getStringCellValue());
//                        //商品编码
//                        goodsExcelVo.setNumber(row.getCell(1).getStringCellValue());
//                        //商品分类id
//                        goodsExcelVo.setCategoryId((int) row.getCell(2).getNumericCellValue());
//                        //规格编码
//                        goodsExcelVo.setSpecNumber(row.getCell(3).getStringCellValue());
//                        //颜色
//                        goodsExcelVo.setColor(row.getCell(4).getStringCellValue());
//                        //尺码
//                        goodsExcelVo.setSize(row.getCell(5).getStringCellValue());
//                        //计量单位
//                        goodsExcelVo.setUnit(row.getCell(6).getStringCellValue());
//                        //默认仓库id
//                        goodsExcelVo.setLocationId((int) row.getCell(7).getNumericCellValue());
//                        //库存预警
//                        goodsExcelVo.setMixStock((int) row.getCell(8).getNumericCellValue());
//
//                    } catch (Exception e) {
////                        throw e;
//                        return new ApiResult<>(505, "数据格式错误");
//                    }
//
//                    goodsList.add(goodsExcelVo);
//                }
//                rowCount++;
//            }
//            //添加系统日志
//            logService.addUserAction(Integer.parseInt(req.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
//                    "/ajax_goods/goods_excel_import","批量导入商品(excel) ,导入数据 : "+JsonUtil.objToString(goodsList)+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
//
//
//        } catch (Exception ex) {
////            workbook = new HSSFWorkbook(fis);
//            return new ApiResult<>(500, ex.getMessage());
//        }
//
//        if (goodsList == null || goodsList.size() == 0) return new ApiResult<>(404, "没有数据");
//
//        var result = goodsService.goodsExcelBatchAdd(goodsList);
//        if (result.getCode() == EnumResultVo.SUCCESS.getIndex()) {
//            return new ApiResult<>(0, "SUCCESS", result.getData());
//        } else {
//            return new ApiResult<>(500, "系统异常，插入数据失败");
//        }
//    }


    /**
     * 根据商品id获取规格json
     *
     * @param id
     * @return
     */
//    @RequestMapping(value = "/json_spec", method = RequestMethod.POST)
//    public ApiResult<String> getJsonSpec(@RequestBody Integer id) {
//        SpecRe re = stockService.getSpeckListById(id);
//        System.out.print(JSON.toJSONString(re));
//        return new ApiResult<>(0, JSON.toJSONString(re));
//    }

    /**
     * 修改商品规格
     *
     * @param model
     * @param request
     * @return
     */
//    @RequestMapping(value = "/goods_edit", method = RequestMethod.POST)
//    public ApiResult<String> goodsEdit(Model model, HttpServletRequest request) {
//        String goodsName = request.getParameter("spname");  //商品名称
//        String number = request.getParameter("spcode");  //商品编号
//        Integer categoryId = Integer.parseInt(request.getParameter("spsort"));  //商品分类id
//        Integer unitId = 0; //计量单位
//        String[] specNumber = request.getParameterValues("code[]");  //规格编号
//        String[] specName = request.getParameterValues("type[]"); //规格名
//        String[] lowQty = request.getParameterValues("min[]"); //最低库存
//        String[] highQty = request.getParameterValues("max[]"); //最高库存
//        String[] specId = request.getParameterValues("specId[]"); //规格id
//
//        if (StringUtils.isEmpty(request.getParameter("spunit"))) return new ApiResult<>(400, "请选择计量单位");
//        unitId = Integer.parseInt(request.getParameter("spunit"));
//
//        Integer locationId = 0; //仓库id
//        //校验
//        if (StringUtils.isEmpty(request.getParameter("locationId"))) return new ApiResult<>(400, "请选择仓库");
//        locationId = Integer.parseInt(request.getParameter("locationId"));
//
//        Integer reservoirId = 0;
//        if (StringUtils.isEmpty(request.getParameter("reservoirId"))) return new ApiResult<>(400, "请选择库区");
//        reservoirId = Integer.parseInt(request.getParameter("reservoirId"));
//
//        Integer shelfId = 0;
//        if (StringUtils.isEmpty(request.getParameter("shelfId"))) return new ApiResult<>(400, "请选择货架");
//        shelfId = Integer.parseInt(request.getParameter("shelfId"));
//
//        //校验
//        Integer goodsId = stockService.ifExsitNumber(number);
//        if (goodsId <= 0) return new ApiResult<>(400, number + ":商品编号不存在");
//        for (int i = 0; i < specNumber.length; i++) {
//            Integer id = stockService.ifExsitSpecNumber(specNumber[i]);  //根据规格编号查询的id
//            if (id > 0 && Integer.parseInt(specId[i]) != id)
//                return new ApiResult<>(400, specNumber[i] + ":规格编号已存在，请勿重复添加");
//            if (Integer.parseInt(specId[i]) == 0) {
//                for (int j = i + 1; j < specNumber.length; j++) {
//                    if (specNumber[i].equals(specNumber[j])) {
//                        return new ApiResult<>(400, "存在相同的规格编号");
//                    }
//                }
//            }
//        }
//
//        //添加商品信息
//        stockService.editGoods(goodsName, number, categoryId, unitId, locationId, reservoirId, shelfId, goodsId);
//        //保存规格信息
//        if (specNumber != null && specNumber.length > 0) {
//            for (int i = 0; i < specNumber.length; i++) {
//                stockService.editGoodsSpec(specNumber[i], specName[i], lowQty[i], highQty[i], goodsId, Integer.parseInt(specId[i]), locationId);
//            }
//        }
//        return new ApiResult<>(0, "SUCCESS");
//    }

    /**
     * 商品规格删除
     *
     * @param id
     * @return
     */
//    @RequestMapping(value = "/delete_goods", method = RequestMethod.POST)
//    public ApiResult<Integer> delSpec(@RequestBody Integer id , HttpServletRequest request) {
//        Integer count = stockService.getGooodsById(id).intValue();
//
//        if (count > 0){
//            //添加系统日志
//            logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
//                    "/ajax_goods/delete_goods","商品规格删除 , 商品Id : "+id+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"失败,该商品还有库存");
//            return new ApiResult<>(400, "该商品还有库存" + count + "件,无法删除!");
//        }
//        stockService.deleteGoods(id);
//        //添加系统日志
//        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
//                "/ajax_goods/delete_goods","商品规格删除 , 商品Id : "+id+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
//        return new ApiResult<>(0, "删除成功");
//    }

    /**
     * 添加商品分类
     *
     * @param model
     * @param req
     * @return
     */
    @RequestMapping(value = "/add_goods_category", method = RequestMethod.POST)
    public ApiResult<Integer> addStockCategory(@RequestBody DataRow model, HttpServletRequest req) {
        String name = model.getString("name");
        Integer pId = Integer.parseInt(model.getString("parentId"));
        String pname = model.getString("pname");
        Integer id = Integer.parseInt(model.getString("id"));
        if (stockService.getCateIdByNameAndParentId(id, name) > 0) return new ApiResult<>(400, "此上级分类下已存在相同的子分类");
        stockService.addStockCategory(name, pId, Integer.parseInt(model.getString("id")));
        //添加系统日志
        logService.addUserAction(Integer.parseInt(req.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_goods/add_goods_category","添加商品分类 , 分类名 : "+name+"  , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");
        log.info("添加分类成功：{parentId:"+id+",parentName:"+pname+",name:"+name+"}");
        return new ApiResult<>(0, "新增成功");
    }

    /**
     * 删除商品分类
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/del_goods_category", method = RequestMethod.POST)
    public ApiResult<Integer> delStockCategory(@RequestBody Integer id ,HttpServletRequest req) {
        ResultVo<Integer> resultVo = stockService.delStockCategory(id);
        if (resultVo.getCode() > 0) return new ApiResult<>(404, resultVo.getMsg());
        //添加系统日志
        logService.addUserAction(Integer.parseInt(req.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
                "/ajax_goods/add_goods_category","删除商品分类 , id : "+id+"  , 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),resultVo.getMsg());

        return new ApiResult<>(0, "删除成功");
    }

    /**
     * 关键词搜索商品
     *
     * @return
     */
    @RequestMapping(value = "/goods_spec_search_by_number", method = RequestMethod.POST)
    public ApiResult<List<GoodsSearchShowVo>> searchGoodsDetail(@RequestBody GoodsSearchReq req) {
        ResultVo<List<GoodsSearchShowVo>> resultVo = new ResultVo<>();
        List<GoodsSearchShowVo> goods = goodsService.getGoodsSpecByNumberForPurchase(req.getKey(), 10);

        return new ApiResult<>(0, "SUCCESS", goods);
    }

//    /**
//     * 根据商品sku编码获取商品规格信息
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/goods_spec_by_number", method = RequestMethod.POST)
//    public ApiResult<GoodsSpecDetailVo> getGoodsSpecDetail(@RequestBody GoodsSpecInReq request) {
//        ResultVo<GoodsSpecDetailVo> resultVo = new ResultVo<>();
//        GoodsSpecDetailVo goods = goodsService.getGoodsSpecDetailByNumber(request.getSpecNumber());
//        if(goods==null) return new ApiResult<>(404,"NOT FOUND");
//
//        //查询采购单数据
//
//        return new ApiResult<>(0, "SUCCESS", goods);
//    }

    /**
     * 获取分类规格list  (添加商品、修改商品 规格下拉)
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/get_spec_attr_list", method = RequestMethod.POST)
    public ApiResult<SpecListResp> goodsSpecList(HttpServletRequest request) {
        List<GoodsCategoryAttributeEntity> specList = goodsService.getSpecByCategory(1);
//        List<CategoryAttributeValueResp> colors = new ArrayList<>();
//        List<CategoryAttributeValueResp> sizes = new ArrayList<>();
//        List<CategoryAttributeValueResp> styles = new ArrayList<>();
//
//        if (specList == null || specList.size() == 0) return new ApiResult<>(0, "没有数据");
//
//
//        //查询规格-颜色
//        GoodsCategoryAttributeEntity colorResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("COLOR")).findFirst().orElse(null);
//        if (colorResult != null) {
//            colors = JSONArray.parseArray(colorResult.getValueText(), CategoryAttributeValueResp.class);
//        }
//        //查询规格-尺码
//        GoodsCategoryAttributeEntity sizeResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("SIZE")).findFirst().orElse(null);
//        if (sizeResult != null) {
//            sizes = JSONArray.parseArray(sizeResult.getValueText(), CategoryAttributeValueResp.class);
//        }
//        //查询款式
//        GoodsCategoryAttributeEntity styleResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("STYLE")).findFirst().orElse(null);
//        if (styleResult != null) {
//            styles = JSONArray.parseArray(styleResult.getValueText(), CategoryAttributeValueResp.class);
//        }
//
//        SpecListResp resp = new SpecListResp();
//        resp.setColor(colors);
//        resp.setSize(sizes);
//        resp.setStyle(styles);

        GoodsCategoryAttributeEntity colorResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("COLOR")).findFirst().orElse(null);
        GoodsCategoryAttributeEntity sizeResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("SIZE")).findFirst().orElse(null);
        GoodsCategoryAttributeEntity styleResult = specList.stream().filter(r -> r.getCode().equalsIgnoreCase("STYLE")).findFirst().orElse(null);
        SpecListResp resp = new SpecListResp();
        resp.setColor(colorResult.getValues());
        resp.setSize(sizeResult.getValues());
       resp.setStyle(styleResult.getValues());

        return new ApiResult<>(0, "SUCCESS", resp);
    }

    /**
     * 添加商品（20190701新版本）
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/goods_add2", method = RequestMethod.POST)
    public ApiResult<String> goodsAdd2(Model model, HttpServletRequest request) {
        log.info("AJAX添加商品页面------"+ request.getSession().getAttribute("userName"));
        ErpGoodsAddVo goodsAddVo = new ErpGoodsAddVo();
        String title = request.getParameter("title"); // 商品名称
        if (StringUtils.isEmpty(title)) return new ApiResult<>(400, "请填写商品名称");

        String number = request.getParameter("number").toUpperCase();  //商品编号
        if (StringUtils.isEmpty(number)) return new ApiResult<>(400, "请填写商品编码");

        if (stockService.ifExsitNumber(number) > 0) return new ApiResult<>(400, number + ":商品编号已存在");

        String category = request.getParameter("category"); // 分类
        if (StringUtils.isEmpty(request.getParameter("categoryId")) || request.getParameter("categoryId") == "0")
            return new ApiResult<>(400, "请选择分类");
        Integer categoryId = Integer.parseInt(request.getParameter("categoryId"));  //商品分类id
        Integer unitId = 0; //计量单位
        if (StringUtils.isEmpty(request.getParameter("spunit"))) return new ApiResult<>(400, "请选择计量单位");
        unitId = Integer.parseInt(request.getParameter("spunit"));

        String sizeImg = request.getParameter("sizeImg");
        goodsAddVo.setSizeImg(sizeImg);
        Integer locationId = 1; //仓库id
//        if (StringUtils.isEmpty(request.getParameter("locationId"))) return new ApiResult<>(400, "请选择仓库");
//        locationId = Integer.parseInt(request.getParameter("locationId"));
        double cost_price = Double.parseDouble(request.getParameter("cost_price"));
        double salePrice = Double.parseDouble(request.getParameter("salePrice"));
        double freight = Double.parseDouble(request.getParameter("freight"));

/*        int reservoirId = 0;
        if (StringUtils.isEmpty(request.getParameter("reservoirId"))) return new ApiResult<>(400, "请选择库区");
        reservoirId = Integer.parseInt(request.getParameter("reservoirId"));

        int shelfId = 0;
        if (StringUtils.isEmpty(request.getParameter("shelfId"))) return new ApiResult<>(400, "请选择货架");
        shelfId = Integer.parseInt(request.getParameter("shelfId"));*/
        String brand="0";
        if(!StringUtils.isEmpty(request.getParameter("brand")))brand=request.getParameter("brand");

        String jijie="";
        if(!StringUtils.isEmpty(request.getParameter("jijie")))jijie=request.getParameter("jijie");
        String fenlei="";
        if(!StringUtils.isEmpty(request.getParameter("fenlei")))fenlei=request.getParameter("fenlei");
        String fengge="";
        if(!StringUtils.isEmpty(request.getParameter("fengge")))fengge=request.getParameter("fengge");
        String nianfen="";
        if(!StringUtils.isEmpty(request.getParameter("nianfen")))nianfen=request.getParameter("nianfen");
        if(!StringUtils.isEmpty(request.getParameter("nianfen"))) goodsAddVo.setErpContactId(Integer.parseInt(request.getParameter("client")));
        else goodsAddVo.setErpContactId(0);

        //面料、尺寸、重量、备注
        String mianliao = request.getParameter("mianliao");
        goodsAddVo.setAttr5(mianliao);
        String beizhu = request.getParameter("beizhu");
        goodsAddVo.setRemark(beizhu);
        float yichang = Float.parseFloat(request.getParameter("yichang"));
        goodsAddVo.setLength(yichang);
        float xiuchang = Float.parseFloat(request.getParameter("xiuchang"));
        goodsAddVo.setHeight(xiuchang);
        float jiankuo = Float.parseFloat(request.getParameter("jiankuo"));
        goodsAddVo.setWidth1(jiankuo);
        float xiongkuo = Float.parseFloat(request.getParameter("xiongkuo"));
        goodsAddVo.setWidth(xiongkuo);
        float yaokuo = Float.parseFloat(request.getParameter("yaokuo"));
        goodsAddVo.setWidth2(yaokuo);
        float tunkuo = Float.parseFloat(request.getParameter("tunkuo"));
        goodsAddVo.setWidth3(tunkuo);
        float zhongliang = Float.parseFloat(request.getParameter("zhongliang"));
        goodsAddVo.setWeight(zhongliang);


        //商品规格
        String[] specNumber = request.getParameterValues("spec_code[]");
        if (specNumber == null || specNumber.length == 0) return new ApiResult<>(400, "请设置商品规格");

        String[] specImage = request.getParameterValues("spec_image[]");//规格图片

        //商品规格
        String[] spec_color_id = request.getParameterValues("spec_color_id[]");
        String[] spec_color = request.getParameterValues("spec_color[]");

        String[] spec_size = request.getParameterValues("spec_size[]");
        String[] spec_size_id = request.getParameterValues("spec_size_id[]");

        String[] spec_style_id = request.getParameterValues("spec_style_id[]");
        String[] spec_style = request.getParameterValues("spec_style[]");
        //计算商品规格数量
        int colorTotal = spec_color_id != null ? spec_color_id.length : 0;
        int sizeTotal = spec_size_id != null ? spec_size_id.length : 0;
        int styleTotal = spec_style_id != null ? spec_style_id.length : 0;

        List<GoodsSpecAttrEntity> colors = new ArrayList<>();
        if (colorTotal > 0) {
            for (int i = 0; i < colorTotal; i++) {
                GoodsSpecAttrEntity color = new GoodsSpecAttrEntity();
                color.setK("颜色");
                color.setKid(1);
                color.setType("color");
                color.setV(spec_color[i]);
                color.setImg(specImage[i]);
                try {
                    color.setVid(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    color.setVid(0);
                }
                colors.add(color);
            }
            goodsAddVo.setColors(colors);
        }
        List<GoodsSpecAttrEntity> sizes = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < sizeTotal; i++) {
                GoodsSpecAttrEntity size = new GoodsSpecAttrEntity();
                size.setK("尺码");
                size.setKid(2);
                size.setType("size");
                size.setV(spec_size[i]);
                try {
                    size.setVid(Integer.valueOf(spec_size_id[i]));
                } catch (Exception e) {
                    size.setVid(0);
                }
                sizes.add(size);
            }
            goodsAddVo.setSizes(sizes);
        }
        List<GoodsSpecAttrEntity> styles = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < styleTotal; i++) {
                GoodsSpecAttrEntity style = new GoodsSpecAttrEntity();
                style.setK("款式");
                style.setKid(3);
                style.setType("style");
                style.setV(spec_style[i]);
                try {
                    style.setVid(Integer.valueOf(spec_style_id[i]));
                } catch (Exception e) {
                    style.setVid(0);
                }
                styles.add(style);
            }
            goodsAddVo.setStyles(styles);
        }


        String[] spec_quantity = request.getParameterValues("spec_quantity[]");
/*        String lowQty = request.getParameter("lowQty");
        String highQty = request.getParameter("highQty");*/

        goodsAddVo.setCategory(category);
        goodsAddVo.setAttr1(jijie);
        goodsAddVo.setAttr2(fenlei);
        goodsAddVo.setAttr3(fengge);
        goodsAddVo.setAttr4(nianfen);
        goodsAddVo.setCategoryId(categoryId);
        goodsAddVo.setLocationId(locationId);
        goodsAddVo.setCostPrice(cost_price);
        goodsAddVo.setSalePrice(salePrice);
        goodsAddVo.setFreight(freight);
        number = number.replace(" ", "");
        number = number.replaceAll("\\s*", "");
        goodsAddVo.setNumber(number.trim());
        //goodsAddVo.setReservoirId(reservoirId);
        //goodsAddVo.setShelfId(shelfId);
        goodsAddVo.setBrand(brand);
        goodsAddVo.setTitle(title);
        goodsAddVo.setUnitId(unitId);
        goodsAddVo.setColors(colors);
        goodsAddVo.setSizes(sizes);
        goodsAddVo.setStyles(styles);

        /**********组合要添加的商品数据***********/
        List<ErpGoodsAddSpecVo> goodsSpecList = new ArrayList<>();
        if (sizeTotal == 0) {
            //只有 颜色color 规格
            for (int i = 0; i < colorTotal; i++) {
                ErpGoodsAddSpecVo spec = new ErpGoodsAddSpecVo();
                spec.setImg(specImage[i]);
                spec.setLowQty(0);
                spec.setHighQty(0);
                try {
                    spec.setCostPrice(Float.valueOf(spec_quantity[i]));
                    // spec.setQuantity(Long.valueOf(spec_quantity[i]));
                } catch (Exception e) {
                    spec.setCostPrice(0.0f);
                }
                spec.setColor(spec_color[i]);
                String specNum = specNumber[i].replaceAll("\\s*", "").toUpperCase();
                spec.setSpecNumber(specNum);
                try {
                    spec.setColorId(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    spec.setColorId(0);
                }

                spec.setSizeId(0);
                spec.setStyle("");
                spec.setStyleId(0);
                goodsSpecList.add(spec);
            }
        } else {
            //有尺码size 规格
            if (styleTotal == 0) {
                //没有款式
                int total = colorTotal * sizeTotal;
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                        goodsSpec.setImg(specImage[i]);
                        goodsSpec.setLowQty(0);
                        goodsSpec.setHighQty(0);
                        try {
                            goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                        } catch (Exception e) {
                            goodsSpec.setQuantity(0l);
                        }
                        goodsSpec.setColor(spec_color[i]);
                        try {
                            goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                        } catch (Exception e) {
                            goodsSpec.setColorId(0);
                        }
                        goodsSpec.setSpecNumber(specNumber[k].replaceAll("\\s*", "").toUpperCase());
                        goodsSpec.setSize(spec_size[j]);
                        try {
                            goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                        } catch (Exception e) {
                            goodsSpec.setSizeId(0);
                        }
                        goodsSpec.setStyle("");
                        goodsSpec.setStyleId(0);

                        goodsSpecList.add(goodsSpec);
                        k++;
                    }
                }
            } else {
                //有款式
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        for (int h = 0; h < styleTotal; h++) {
                            ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                            goodsSpec.setImg(specImage[i]);
                            goodsSpec.setLowQty(0);
                            goodsSpec.setHighQty(0);
                            try {
                                goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                            } catch (Exception e) {
                                goodsSpec.setQuantity(0l);
                            }
                            goodsSpec.setColor(spec_color[i]);
                            try {
                                goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                            } catch (Exception e) {
                                goodsSpec.setColorId(0);
                            }
                            goodsSpec.setSpecNumber(specNumber[k].replaceAll("\\s*", "").toUpperCase());
                            goodsSpec.setSize(spec_size[j]);
                            try {
                                goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                            } catch (Exception e) {
                                goodsSpec.setSizeId(0);
                            }
                            goodsSpec.setStyle(spec_style[h]);
                            try {
                                goodsSpec.setStyleId(Integer.valueOf(spec_style_id[h]));
                            } catch (Exception e) {
                                goodsSpec.setStyleId(0);
                            }

                            goodsSpecList.add(goodsSpec);
                            k++;
                        }
                    }
                }
            }
        }
        goodsAddVo.setImage(colors.get(0).getImg());
        goodsAddVo.setSpecList(goodsSpecList);
        
        ResultVo<Integer> resultVo = goodsService.goodsAdd(goodsAddVo);
        //添加系统日志
        logService.addUserAction(DataConfigObject.getInstance().getLoginUserId(), EnumUserActionType.Modify,
                "/ajax_goods/goods_add2","添加商品 , 商品编号 : "+number+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),resultVo.getMsg());

        log.info("添加商品完成{number:"+ goodsAddVo.getNumber()+"}"+ JSONObject.toJSONString(goodsAddVo.getSpecList()));
        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS");
        } else {
            return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
        }

    }


    @RequestMapping(value = "/goods_add2_spec", method = RequestMethod.POST)
    public ApiResult<String> goodsAdd2Spec(Model model, HttpServletRequest request) {
        log.info("AJAX添加商品页面------"+ request.getSession().getAttribute("userName"));
        ErpGoodsAddVo goodsAddVo = new ErpGoodsAddVo();
        goodsAddVo.setId(Integer.parseInt(request.getParameter("id")));

        //商品规格
        String[] specNumber = request.getParameterValues("spec_code[]");
        if (specNumber == null || specNumber.length == 0) return new ApiResult<>(400, "请设置商品规格");

        String[] specImage = request.getParameterValues("spec_image[]");//规格图片

        //商品规格
        String[] spec_color_id = request.getParameterValues("spec_color_id[]");
        String[] spec_color = request.getParameterValues("spec_color[]");

        String[] spec_size = request.getParameterValues("spec_size[]");
        String[] spec_size_id = request.getParameterValues("spec_size_id[]");

        String[] spec_style_id = request.getParameterValues("spec_style_id[]");
        String[] spec_style = request.getParameterValues("spec_style[]");
        //计算商品规格数量
        int colorTotal = spec_color_id != null ? spec_color_id.length : 0;
        int sizeTotal = spec_size_id != null ? spec_size_id.length : 0;
        int styleTotal = spec_style_id != null ? spec_style_id.length : 0;

        List<GoodsSpecAttrEntity> colors = new ArrayList<>();
        if (colorTotal > 0) {
            for (int i = 0; i < colorTotal; i++) {
                GoodsSpecAttrEntity color = new GoodsSpecAttrEntity();
                color.setK("颜色");
                color.setKid(1);
                color.setType("color");
                color.setV(spec_color[i]);
                color.setImg(specImage[i]);
                try {
                    color.setVid(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    color.setVid(0);
                }
                colors.add(color);
            }
            goodsAddVo.setColors(colors);
        }
        List<GoodsSpecAttrEntity> sizes = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < sizeTotal; i++) {
                GoodsSpecAttrEntity size = new GoodsSpecAttrEntity();
                size.setK("尺码");
                size.setKid(2);
                size.setType("size");
                size.setV(spec_size[i]);
                try {
                    size.setVid(Integer.valueOf(spec_size_id[i]));
                } catch (Exception e) {
                    size.setVid(0);
                }
                sizes.add(size);
            }
            goodsAddVo.setSizes(sizes);
        }
        List<GoodsSpecAttrEntity> styles = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < styleTotal; i++) {
                GoodsSpecAttrEntity style = new GoodsSpecAttrEntity();
                style.setK("款式");
                style.setKid(3);
                style.setType("style");
                style.setV(spec_style[i]);
                try {
                    style.setVid(Integer.valueOf(spec_style_id[i]));
                } catch (Exception e) {
                    style.setVid(0);
                }
                styles.add(style);
            }
            goodsAddVo.setStyles(styles);
        }


        String[] spec_quantity = request.getParameterValues("spec_quantity[]");
        goodsAddVo.setColors(colors);
        goodsAddVo.setSizes(sizes);
        goodsAddVo.setStyles(styles);

        /**********组合要添加的商品数据***********/
        List<ErpGoodsAddSpecVo> goodsSpecList = new ArrayList<>();
        if (sizeTotal == 0) {
            //只有 颜色color 规格
            for (int i = 0; i < colorTotal; i++) {
                ErpGoodsAddSpecVo spec = new ErpGoodsAddSpecVo();
                spec.setImg(specImage[i]);
                spec.setLowQty(0);
                spec.setHighQty(0);
                try {
                    spec.setQuantity(Long.valueOf(spec_quantity[i]));
                } catch (Exception e) {
                    spec.setQuantity(0l);
                }
                spec.setColor(spec_color[i]);
                spec.setSpecNumber(specNumber[i].replaceAll("\\s*", ""));
                try {
                    spec.setColorId(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    spec.setColorId(0);
                }

                spec.setSizeId(0);
                spec.setStyle("");
                spec.setStyleId(0);
                goodsSpecList.add(spec);
            }
        } else {
            //有尺码size 规格
            if (styleTotal == 0) {
                //没有款式
                int total = colorTotal * sizeTotal;
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                        goodsSpec.setImg(specImage[i]);
                        goodsSpec.setLowQty(0);
                        goodsSpec.setHighQty(0);
                        try {
                            goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                        } catch (Exception e) {
                            goodsSpec.setQuantity(0l);
                        }
                        goodsSpec.setColor(spec_color[i]);
                        try {
                            goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                        } catch (Exception e) {
                            goodsSpec.setColorId(0);
                        }
                        goodsSpec.setSpecNumber(specNumber[k]);
                        goodsSpec.setSize(spec_size[j]);
                        try {
                            goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                        } catch (Exception e) {
                            goodsSpec.setSizeId(0);
                        }
                        goodsSpec.setStyle("");
                        goodsSpec.setStyleId(0);

                        goodsSpecList.add(goodsSpec);
                        k++;
                    }
                }
            } else {
                //有款式
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        for (int h = 0; h < styleTotal; h++) {
                            ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                            goodsSpec.setImg(specImage[i]);
                            goodsSpec.setLowQty(0);
                            goodsSpec.setHighQty(0);
                            try {
                                goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                            } catch (Exception e) {
                                goodsSpec.setQuantity(0l);
                            }
                            goodsSpec.setColor(spec_color[i]);
                            try {
                                goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                            } catch (Exception e) {
                                goodsSpec.setColorId(0);
                            }
                            goodsSpec.setSpecNumber(specNumber[k]);
                            goodsSpec.setSize(spec_size[j]);
                            try {
                                goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                            } catch (Exception e) {
                                goodsSpec.setSizeId(0);
                            }
                            goodsSpec.setStyle(spec_style[h]);
                            try {
                                goodsSpec.setSizeId(Integer.valueOf(spec_style_id[h]));
                            } catch (Exception e) {
                                goodsSpec.setStyleId(0);
                            }

                            goodsSpecList.add(goodsSpec);
                            k++;
                        }
                    }
                }
            }
        }
        goodsAddVo.setImage(colors.get(0).getImg());
        goodsAddVo.setSpecList(goodsSpecList);
        ResultVo<Integer> resultVo = goodsService.goodsAddSpec(goodsAddVo);

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS");
        } else {
            return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
        }

    }


    @RequestMapping(value = "/getGoodsSpecList", method = RequestMethod.POST)
    public ApiResult<List<ErpGoodsSpecListVo>> getGoodsSpecList(@RequestBody Integer goodsId, HttpServletRequest req) {
        List<ErpGoodsSpecListVo> specList = goodsService.getSpecByGoodsId(goodsId);
        return new ApiResult<>(0, "SUCCESS", specList);
    }

    /**
     * 修改商品（20190701新版本）
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/goods_edit2", method = RequestMethod.POST)
    public ApiResult<String> goodsEdit2(Model model, HttpServletRequest request) {
        ErpGoodsAddVo goodsAddVo = new ErpGoodsAddVo();
        String id = request.getParameter("goodsId"); // 商品id
        if (StringUtils.isEmpty(id)) return new ApiResult<>(400, "数据错误，请刷新后再试");
        Integer goodsId = Integer.parseInt(id);

        var g = goodsService.getById(goodsId);
        if (g == null) return new ApiResult<>(400, "数据错误，请刷新后再试");

        String title = request.getParameter("title");  //商品名称
        if (StringUtils.isEmpty(title)) return new ApiResult<>(400, "请填写商品名称");

        String number = request.getParameter("good_number");  //商品编号
        if (StringUtils.isEmpty(number)) return new ApiResult<>(400, "请填写商品编码");
        else if (number.equals(g.getNumber()) == false) {
            if (stockService.ifExsitNumber(number) > 0) return new ApiResult<>(400, number + ":商品编号已存在");
        }

        double costPrice=0d;
        if(!StringUtils.isEmpty(request.getParameter("costPrice"))){
            costPrice=Double.parseDouble(request.getParameter("costPrice"));
        }
        double salePrice=0d;
        if(!StringUtils.isEmpty(request.getParameter("salePrice"))){
            salePrice=Double.parseDouble(request.getParameter("salePrice"));
        }
        String attr1="";
        if(!StringUtils.isEmpty(request.getParameter("attr1"))){
            attr1=request.getParameter("attr1");
        }
        String attr2="";
        if(!StringUtils.isEmpty(request.getParameter("attr2"))){
            attr2=request.getParameter("attr2");
        }
        String attr3="";
        if(!StringUtils.isEmpty(request.getParameter("attr3"))){
            attr3=request.getParameter("attr3");
        }
        String attr4="";
        if(!StringUtils.isEmpty(request.getParameter("attr4"))){
            attr4=request.getParameter("attr4");
        }
        String attr5="";
        if(!StringUtils.isEmpty(request.getParameter("attr5"))){
            attr5=request.getParameter("attr5");
        }

        String length="";
        if(!StringUtils.isEmpty(request.getParameter("length"))){
            length=request.getParameter("length");
        }
        String height="";
        if(!StringUtils.isEmpty(request.getParameter("height"))){
            height=request.getParameter("height");
        }
        String width1="";
        if(!StringUtils.isEmpty(request.getParameter("width1"))){
            width1=request.getParameter("width1");
        }
        String width="";
        if(!StringUtils.isEmpty(request.getParameter("width"))){
            width=request.getParameter("width");
        }
        String width2="";
        if(!StringUtils.isEmpty(request.getParameter("width2"))){
            width2=request.getParameter("width2");
        }
        String width3="";
        if(!StringUtils.isEmpty(request.getParameter("width3"))){
            width3=request.getParameter("width3");
        }
        String weight="";
        if(!StringUtils.isEmpty(request.getParameter("weight"))){
            weight=request.getParameter("weight");
        }
        String remark="";
        if(!StringUtils.isEmpty(request.getParameter("remark"))){
            remark=request.getParameter("remark");
        }


        // 分类
        if (StringUtils.isEmpty(request.getParameter("categoryId")) || request.getParameter("categoryId") == "0")
            return new ApiResult<>(400, "请选择分类");
        Integer categoryId = Integer.parseInt(request.getParameter("categoryId"));  //商品分类id

        /*Integer unitId = 0; //计量单位
        if (StringUtils.isEmpty(request.getParameter("spunit"))) return new ApiResult<>(400, "请选择计量单位");
        unitId = Integer.parseInt(request.getParameter("spunit"));*/

/*        Integer locationId = 0; //仓库id
        if (StringUtils.isEmpty(request.getParameter("locationId"))) return new ApiResult<>(400, "请选择仓库");
        locationId = Integer.parseInt(request.getParameter("locationId"));*/

/*        int reservoirId = 0;
        if (StringUtils.isEmpty(request.getParameter("reservoirId"))) return new ApiResult<>(400, "请选择库区");
        reservoirId = Integer.parseInt(request.getParameter("reservoirId"));

        int shelfId = 0;
        if (StringUtils.isEmpty(request.getParameter("shelfId"))) return new ApiResult<>(400, "请选择货架");
        shelfId = Integer.parseInt(request.getParameter("shelfId"));*/
       /* String brand="";
        if(!StringUtils.isEmpty(request.getParameter("brand")))brand=request.getParameter("brand");
        //商品规格
        String[] specNumber = request.getParameterValues("spec_code[]");  //规格编号
        if (specNumber == null || specNumber.length == 0) return new ApiResult<>(400, "请设置商品规格");*/

        // 商品规格
        String[] spec_color_id = request.getParameterValues("spec_color_id[]");//颜色id
        String[] spec_color = request.getParameterValues("spec_color[]");//颜色值

        String[] spec_size = request.getParameterValues("spec_size[]");//尺码值
        String[] spec_size_id = request.getParameterValues("spec_size_id[]");//尺码id

        String[] spec_style_id = request.getParameterValues("spec_style_id[]");//颜色id
        String[] spec_style = request.getParameterValues("spec_style[]");//颜色值
        //计算商品规格数量
        int colorTotal = spec_color_id != null ? spec_color_id.length : 0;
        int sizeTotal = spec_size_id != null ? spec_size_id.length : 0;
        int styleTotal = spec_style_id != null ? spec_style_id.length : 0;
        //颜色规格color
        List<GoodsSpecAttrEntity> colors = new ArrayList<>();
        if (colorTotal > 0) {
            for (int i = 0; i < colorTotal; i++) {
                GoodsSpecAttrEntity color = new GoodsSpecAttrEntity();
                color.setK("颜色");
                color.setKid(1);
                color.setType("color");
                color.setV(spec_color[i]);
                try {
                    color.setVid(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    color.setVid(0);
                }
                colors.add(color);
            }
            goodsAddVo.setColors(colors);
        }
        //尺码规格size
        List<GoodsSpecAttrEntity> sizes = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < sizeTotal; i++) {
                GoodsSpecAttrEntity size = new GoodsSpecAttrEntity();
                size.setK("尺码");
                size.setKid(2);
                size.setType("size");
                size.setV(spec_size[i]);
                try {
                    size.setVid(Integer.valueOf(spec_size_id[i]));
                } catch (Exception e) {
                    size.setVid(0);
                }
                sizes.add(size);
            }
            goodsAddVo.setSizes(sizes);
        }
        //款式规格style
        List<GoodsSpecAttrEntity> styles = new ArrayList<>();
        if (sizeTotal > 0) {
            for (int i = 0; i < styleTotal; i++) {
                GoodsSpecAttrEntity style = new GoodsSpecAttrEntity();
                style.setK("款式");
                style.setKid(3);
                style.setType("style");
                style.setV(spec_style[i]);
                try {
                    style.setVid(Integer.valueOf(spec_style_id[i]));
                } catch (Exception e) {
                    style.setVid(0);
                }
                styles.add(style);
            }
            goodsAddVo.setStyles(styles);
        }


        String[] spec_quantity = request.getParameterValues("spec_quantity[]"); //规格名
/*        String lowQty = request.getParameter("lowQty"); //最低库存
        String highQty = request.getParameter("highQty");//最高库存*/
/*        goodsAddVo.setCategory(category);
        goodsAddVo.setLocationId(locationId);*/
        goodsAddVo.setNumber(number);
        goodsAddVo.setCategoryId(categoryId);
        //goodsAddVo.setBrand(brand);
        goodsAddVo.setSalePrice(salePrice);
        goodsAddVo.setCostPrice(costPrice);
       /* goodsAddVo.setReservoirId(reservoirId);
        goodsAddVo.setShelfId(shelfId);*/
        goodsAddVo.setTitle(title);
        //goodsAddVo.setUnitId(unitId);
        goodsAddVo.setColors(colors);
        goodsAddVo.setSizes(sizes);
        goodsAddVo.setStyles(styles);
        goodsAddVo.setAttr1(attr1);
        goodsAddVo.setAttr2(attr2);
        goodsAddVo.setAttr3(attr3);
        goodsAddVo.setAttr4(attr4);
        goodsAddVo.setAttr5(attr5);
        goodsAddVo.setRemark(remark);
        goodsAddVo.setLength(StringUtils.isEmpty(length)?0.0f:Float.parseFloat(length));
        goodsAddVo.setWeight(StringUtils.isEmpty(weight)?0.0f:Float.parseFloat(weight));
        goodsAddVo.setHeight(StringUtils.isEmpty(height)?0.0f:Float.parseFloat(height));
        goodsAddVo.setWidth(StringUtils.isEmpty(width)?0.0f:Float.parseFloat(width));
        goodsAddVo.setWidth1(StringUtils.isEmpty(width1)?0.0f:Float.parseFloat(width1));
        goodsAddVo.setWidth2(StringUtils.isEmpty(width2)?0.0f:Float.parseFloat(width2));
        goodsAddVo.setWidth3(StringUtils.isEmpty(width3)?0.0f:Float.parseFloat(width3));




        /**********组合要添加的商品数据***********/
      /*  List<ErpGoodsAddSpecVo> goodsSpecList = new ArrayList<>();
        if (sizeTotal == 0) {
            //只有 颜色color 规格
            for (int i = 0; i < colorTotal; i++) {
                ErpGoodsAddSpecVo spec = new ErpGoodsAddSpecVo();
                spec.setLowQty(0);
                spec.setHighQty(0);
                try {
                    spec.setQuantity(Long.valueOf(spec_quantity[i]));
                } catch (Exception e) {
                    spec.setQuantity(0l);
                }
                spec.setColor(spec_color[i]);
                spec.setSpecNumber(specNumber[i]);
                try {
                    spec.setColorId(Integer.valueOf(spec_color_id[i]));
                } catch (Exception e) {
                    spec.setColorId(0);
                }
                spec.setSizeId(0);
                spec.setStyle("");
                spec.setStyleId(0);
                goodsSpecList.add(spec);
            }
        } else {
            //有尺码size 规格
            if (styleTotal == 0) {
                //没有款式
                int total = colorTotal * sizeTotal;
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                        goodsSpec.setLowQty(0);
                        goodsSpec.setHighQty(0);
                        try {
                            goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                        } catch (Exception e) {
                            goodsSpec.setQuantity(0l);
                        }
                        goodsSpec.setColor(spec_color[i]);
                        try {
                            goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                        } catch (Exception e) {
                            goodsSpec.setColorId(0);
                        }
                        goodsSpec.setSpecNumber(specNumber[k]);
                        goodsSpec.setSize(spec_size[j]);
                        try {
                            goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                        } catch (Exception e) {
                            goodsSpec.setSizeId(0);
                        }
                        goodsSpec.setStyle("");
                        goodsSpec.setStyleId(0);

                        goodsSpecList.add(goodsSpec);
                        k++;
                    }
                }
            } else {
                //有款式
                int k = 0;
                for (int i = 0; i < colorTotal; i++) {

                    for (int j = 0; j < sizeTotal; j++) {
                        for (int h = 0; h < styleTotal; h++) {
                            ErpGoodsAddSpecVo goodsSpec = new ErpGoodsAddSpecVo();
                            goodsSpec.setLowQty(0);
                            goodsSpec.setHighQty(0);
                            try {
                                goodsSpec.setQuantity(Long.valueOf(spec_quantity[i]));
                            } catch (Exception e) {
                                goodsSpec.setQuantity(0l);
                            }
                            goodsSpec.setColor(spec_color[i]);
                            try {
                                goodsSpec.setColorId(Integer.valueOf(spec_color_id[i]));
                            } catch (Exception e) {
                                goodsSpec.setColorId(0);
                            }
                            goodsSpec.setSpecNumber(specNumber[k]);
                            goodsSpec.setSize(spec_size[j]);
                            try {
                                goodsSpec.setSizeId(Integer.valueOf(spec_size_id[j]));
                            } catch (Exception e) {
                                goodsSpec.setSizeId(0);
                            }
                            goodsSpec.setStyle(spec_style[h]);
                            try {
                                goodsSpec.setSizeId(Integer.valueOf(spec_style_id[h]));
                            } catch (Exception e) {
                                goodsSpec.setStyleId(0);
                            }

                            goodsSpecList.add(goodsSpec);
                            k++;
                        }
                    }
                }
            }
        }
        goodsAddVo.setSpecList(goodsSpecList);*/
        ResultVo<Integer> resultVo = goodsService.goodsBaseInfoEdit(goodsId, goodsAddVo);

        // //添加系统日志
        // logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Modify,
        //         "/ajax_goods/goods_edit2","修改商品（20190701新版本） , 商品Id : "+id+" ,修改前内容 : "+ JsonUtil.objToString(g)+" ,日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),resultVo.getMsg());

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS");
        } else {
            return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
        }

    }

    @RequestMapping(value = "/upd_erp_good_spec_attr", method = RequestMethod.POST)
    public ApiResult<Integer> delStockCategory(@RequestBody DataRow reqData , HttpServletRequest req) {
        goodsService.updErpGoodSpecAttr(reqData.getInt("specId"),reqData.getString("attr1"),reqData.getString("attr2"));
        return new ApiResult<>(0, "修改成功");
    }

    @RequestMapping(value = "/upd_erp_good_spec_purPrice", method = RequestMethod.POST)
    public ApiResult<Integer> updateSpecPurPrice(@RequestBody DataRow reqData , HttpServletRequest req) {
        Integer id = reqData.getInt("id");
        Double purPrice = reqData.getDouble("purPrice");

        goodsService.updateSpecPurPrice(id,purPrice);
        return new ApiResult<>(0, "修改成功");
    }
}
